import Vue from 'vue'
import { login, getInfo, logout, switchComp } from '@/api/login'
import { settingInfo, changePwd } from '@/api/system/system'
import { basicsInfo } from '@/api/system/base'
import { ACCESS_TOKEN, TENANTID } from '@/store/mutation-types'
import { welcome } from '@/utils/common'
import { userTableColumns } from '@/components/Cuscolumn/defaultData'
const userCustomTable = localStorage.getItem('customtable');



const user = {
  state: {
    userId: '',
    token: '',
    tenantId: '',
    name: '',
    welcome: '',
    avatar: '',
    company: {
      companyName: '',
      logo: ''
    },
    currCompId: '',
    admin: false,
    myTeam: [],
    roles: [],
    buttons: [], // 按钮权限
    info: {},
    sysConfig: {},
    basicsInfo: {},
    loginTitle: '登录',
    userType: '',
    customTable: userCustomTable ? JSON.parse(userCustomTable) : {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_TENANTID: (state, tenantId) => {
      state.tenantId = tenantId
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_BUTTONS: (state, buttons) => {
      state.buttons = buttons
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_COMPANY: (state, company) => {
      state.company = company
    },
    SET_MYTEAM: (state, myteam) => {
      state.myTeam = myteam
    },
    SET_CURRCOMPID: (state, currCompId) => {
      state.currCompId = currCompId
    },
    SET_ADMIN: (state, admin) => {
      state.admin = admin
    },
    SET_CONFIG: (state, sysConfig) => {
      state.sysConfig = sysConfig
    },
    SET_BASICSINFO: (state, basicsInfo) => {
      state.basicsInfo = basicsInfo
    },
    SET_LOGIN: (state, loginTitle) => {
      state.loginTitle = loginTitle
    },
    SET_USERTYPE: (state, userType) => {
      state.userType = userType
    },
    /**
     * tableName: 需要存储的表格唯一Name
     * columns 用户自定义表格数据
     */
    SET_CUSTOMTABLE: (state, data) => {
      state.customTable[data.tableName] = data.columns;
      state.customTable = JSON.parse(JSON.stringify(state.customTable));
      localStorage.setItem('customtable', JSON.stringify(state.customTable));
    }
  },

  actions: {
    // 登录
    Login({ commit, state }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          const result = response
          Vue.ls.set(ACCESS_TOKEN, result.token, 12 * 60 * 60 * 1000)
          Vue.ls.set(TENANTID, result.tenantId, 12 * 60 * 60 * 1000)
          commit('SET_TOKEN', result.token)
          commit('SET_TENANTID', result.tenantId)
          localStorage.setItem('tenantId', result.tenantId)

          if (!state.customTable.user) {
            commit('SET_CUSTOMTABLE', {
              tableName: 'user',
              columns: userTableColumns
            })
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const result = response
          if (result.roleIds) {
            commit('SET_ROLES', result.roleIds)
            commit('SET_BUTTONS', result.buttons)
            commit('SET_USERID', result.userId)
            commit('SET_INFO', result)
          } else {
            reject(new Error('getInfo: roles must be a non-null array !'))
          }
          commit('SET_NAME', { name: result.userName, welcome: welcome() })
          commit('SET_AVATAR', result.avatar)
          if (result.company) {
            commit('SET_COMPANY', result.company)
          }
          commit('SET_MYTEAM', result.myTeam)
          commit('SET_CURRCOMPID', result.currCompId)
          commit('SET_ADMIN', result.admin)
          commit('SET_USERTYPE', result.userType)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取网站基础信息 - 暂未启用
    GetSysInfo({ commit }) {
      return new Promise((resolve, reject) => {
        settingInfo().then(response => {
          const result = response
          commit('SET_CONFIG', result.data)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    //获取机构信息
    GetBasicsInfo({ commit }) {
      return new Promise((resolve, reject) => {
        basicsInfo().then(response => {
          const result = response
          commit('SET_BASICSINFO', result.data)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        logout(state.token).then(() => {
          resolve()
        }).catch(() => {
          resolve()
        }).finally(() => {
          commit('SET_TOKEN', '')
          commit('SET_TENANTID', '')
          commit('SET_ROLES', [])
          commit('SET_INFO', {})
          Vue.ls.remove(ACCESS_TOKEN)
        })
      })
    },

    // 修改密码
    ChangePwd(params, obj) {
      console.log(params, obj)
      return new Promise((resolve) => {
        changePwd(obj).then((res) => {
          resolve(res)
        }).catch(() => {
          resolve()
        })
      })
    },

    // 切换
    switchComp({ commit, state }) {
      var params = {
        compId: state.currCompId
      }
      return new Promise((resolve) => {
        switchComp(params).then((res) => {
          resolve(res)
        }).catch(() => {
          resolve()
        })
      })
    }
  }
}

export default user
